import React from 'react';
import { Grid } from '@material-ui/core';
import youtube from './api/youtube';
import {useState,useEffect} from 'react';

import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
import VideoDetail from './components/VideoDetail';

const App =() => {
    const [videos,setVideos] = useState([]);
    const [selectVideo,setSelectVideo] = useState(null);
    // 发起http请求
    async function handleSubmit (searchTerm) {
        const response = await youtube.get( 'search',
            {
                params:{
                    part:'snippet',
                    maxResult:5,
                    key:'AIzaSyBIMY-rXNxW4E-rbnazQxZwFdLNn3SLyEs',
                    q:searchTerm
                }
            }
         );
         setSelectVideo(response.data.items[0]);
         setVideos(response.data.items);
    }

    // 避免刷新页面之后，页面为空(传入空数组，表示只允许effect一次)
    useEffect(()=>{
        handleSubmit("star gardian");
    },[]);

    // 当videoList选中缩略图时，设置当前播放video
    const onVideoSelect = (video)=>{
        setSelectVideo(video);
    }
    
    return (
        <Grid justify='center' container >
            <Grid item xs={12}>
                <Grid container spacing={4}>
                    <Grid item xs={12}>
                        <SearchBar onSubmit={handleSubmit} />
                    </Grid>
                    <Grid item xs={8}>
                        <VideoDetail video={selectVideo}/>
                    </Grid>
                    <Grid item xs={4}>
                        <VideoList videos={videos} onVideoSelect={onVideoSelect}/>
                    </Grid>
                </Grid>
            </Grid>
        </Grid>
    )
}
export default App;